<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="success" @click="handleSubmit"> 保存 </el-button>
    </div>
    <el-table :data="autos" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <div class="filter-container">
            <span class="filter-item text"> 场景名称: </span>
            <el-input v-model="props.row.name" placeholder="请输入场景名称" style="width:200px;" />
            <span class="filter-item text"> 条件: </span>
            <el-radio-group v-model="props.row.logic" class="filter-item">
              <el-radio :label="1">同时满足</el-radio>
              <el-radio :label="2">任一条件满足</el-radio>
            </el-radio-group>
            <span class="filter-item text"> 启动: </span>
            <el-switch
              v-model="props.row.enable"
              class="filter-item"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="onEnableChange(props.row)"
            />
          </div>

          <el-row :gutter="20">
            <el-col :xs="12" :sm="12" :lg="12" class="card-panel-col">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <h2>如果</h2>
                  <el-button class="filter-item" style="float:right;" type="primary" @click="handleAddConditionShow(props.$index)"> 添加条件 </el-button>
                </div>

                <el-table :data="props.row.condition" style="width: 100%">
                  <el-table-column label="设备" align="center" prop="name" />
                  <el-table-column label="位置" align="center" prop="position" />
                  <el-table-column label="引脚编号" align="center" prop="number" />
                  <el-table-column label="条件" align="center" prop="status">
                    <template slot-scope="{row}">
                      <span>{{ row.status | statusFilter(row.values) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center">
                    <template slot-scope="{row}">
                      <el-button type="danger" @click="handleDeleteCondition(props.$index, row.$index)"> 删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
            <el-col :xs="12" :sm="12" :lg="12" class="card-panel-col">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <h2>就执行</h2>
                  <el-button class="filter-item" style="float:right;" type="primary" @click="handleAddRunShow(props.$index)"> 添加动作 </el-button>
                </div>
                <el-table :data="props.row.run" style="width: 100%">
                  <el-table-column label="设备" align="center" prop="name" />
                  <el-table-column label="位置" align="center" prop="position" />
                  <el-table-column label="引脚编号" align="center" prop="引脚编号" />
                  <el-table-column label="动作" align="center" prop="status">
                    <template slot-scope="{row}">
                      <span>{{ row.status | statusFilter(row.values) }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" align="center">
                    <template slot-scope="{row}">
                      <el-button type="danger" @click="handleDeleteRun(props.$index, row.$index)"> 删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="ID" type="index" align="center" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="逻辑" align="center" prop="logic">
        <template slot-scope="{row}">
          <el-tag :type="row.logic | logicTypeFilter">{{ row.logic | logicFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="启动" align="center">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.enable"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="onEnableChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button type="primary" @click="onSet(row)"> 设置 </el-button>
          <!-- <el-button type="danger" @click="handleDelete(row)"> 删除 </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="添加条件" :visible.sync="dialogAddConditionVisible">
      <el-table :data="selectConditionDevices">
        <el-table-column label="设备" align="center" prop="name" />
        <el-table-column label="位置" align="center" prop="position" />
        <el-table-column label="引脚编号" align="center" prop="number" />
        <el-table-column label="选择状态" align="center">
          <template slot-scope="{row}">
            <el-select v-model="row.status" placeholder="请选择">
              <el-option v-for="item in row.values" :key="item.value" :disabled="item.select" :label="item.name" :value="item.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="{row}">
            <el-button type="success" @click="handleAddCondition(row)"> 添加 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="添加动作" :visible.sync="dialogAddRunVisible">
      <el-table :data="selectRunDevices">
        <el-table-column label="设备" align="center" prop="name" />
        <el-table-column label="位置" align="center" prop="position" />
        <el-table-column label="引脚编号" align="center" prop="number" />
        <el-table-column label="选择动作" align="center">
          <template slot-scope="{row}">
            <el-select v-model="row.status" placeholder="请选择">
              <el-option v-for="item in row.values" :key="item.value" :disabled="item.select" :label="item.name" :value="item.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="{row}">
            <el-button type="success" @click="handleAddRun(row)"> 添加 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import { CMD_CONTROL } from '@/utils/cmd'
import { editDevice } from '@/api/device'
const defaultAutos = [
  {
    id: 0,
    name: '场景1',
    enable: 1,
    condition: [],
    run: [],
    logic: 1
  },
  {
    id: 1,
    name: '场景2',
    enable: 0,
    condition: [],
    run: [],
    logic: 1
  },
  {
    id: 2,
    name: '场景3',
    enable: 0,
    condition: [],
    run: [],
    logic: 1
  },
  {
    id: 3,
    name: '场景3',
    enable: 0,
    condition: [],
    run: [],
    logic: 1
  }
]

export default {
  name: 'Auto',
  components: { },
  filters: {
    statusFilter(status, values) {
      for (var i = 0; i < values.length; i++) {
        if (status === values[i].value) {
          return values[i].name
        }
      }
    },
    logicFilter(logic) {
      if (logic === 1) {
        return '同时满足'
      }
      if (logic === 2) {
        return '满足任一条件'
      }
    },
    logicTypeFilter(logic) {
      if (logic === 1) {
        return 'success'
      }
      if (logic === 2) {
        return 'warning'
      }
    }
  },
  data() {
    return {
      tableWidth: '150',
      index: 0,

      autos: defaultAutos,
      selectConditionDevices: [],
      selectRunDevices: [],
      dialogAddConditionVisible: false,
      dialogAddRunVisible: false
    }
  },
  watch: {
  },
  created() {
    this.device = this.$route.query
    console.log('设备信息:')
    console.log(this.device)
    var pin = this.device.value.pin
    for (var i = 0; i < pin.length; i++) {
      if (pin[i].mode === 1) {
        this.selectConditionDevices.push(pin[i])
      }
      if (pin[i].mode === 2) {
        this.selectRunDevices.push(pin[i])
      }
    }

    var autos = this.device.value.autos
    if (autos === undefined) {
      this.autos = defaultAutos
    } else {
      this.autos = autos
    }
    this.subscribe(this.device.pub)
  },
  methods: {
    handleSubmit() {
      this.device.value.autos = this.autos
      editDevice(this.device).then(response => {
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.$router.push({ path: '/device/index' })
        } else this.$message(response.message)
      })
    },
    handleAddConditionShow(index) {
      console.log('添加')
      console.log(index)
      this.index = index
      this.dialogAddConditionVisible = true
    },
    handleAddCondition(row) {
      console.log('>>添加条件')
      this.autos[this.index].condition.push(JSON.parse(JSON.stringify(row)))
      this.dialogAddConditionVisible = false
    },
    handleDeleteCondition(auto_idx, condition_idx) {
      this.autos[auto_idx].condition.splice(condition_idx, 1)
    },
    handleAddRunShow(index) {
      console.log('添加')
      console.log(index)
      this.index = index
      this.dialogAddRunVisible = true
    },
    handleAddRun(row) {
      console.log('>>添加动作')
      console.log(row)
      this.autos[this.index].run.push(JSON.parse(JSON.stringify(row)))
      this.dialogAddRunVisible = false
    },
    handleDeleteRun(auto_idx, run_idx) {
      this.autos[auto_idx].run.splice(run_idx, 1)
    },
    onEnableChange(row) {
    },
    onSet(row) {
      console.log('设置单片机')
      console.log(row)
      var tmp = JSON.parse(JSON.stringify(row))
      //   var conditions;
      var auto = {
        id: tmp.id,
        enable: tmp.enable,
        logic: tmp.logic,
        runs: tmp.run,
        conditions: tmp.condition
      }
      for (var c = 0; c < auto.conditions.length; c++) {
        auto.conditions[c] = {
          pin: auto.conditions[c].number,
          status: auto.conditions[c].status
        }
      }
      for (var r = 0; r < auto.runs.length; r++) {
        auto.runs[r] = {
          pin: auto.runs[r].number,
          status: auto.runs[r].status
        }
      }
      console.log(auto)
      this.publish(this.device.sub, JSON.stringify({
        code: CMD_CONTROL.set_auto.toString(),
        msg: auto
      }))
    },
    subscribe(val) {
      console.log('订阅')
      console.log('topic:' + val)
      this.$mqtt.subscribe(val)
    },
    publish(topic, message) {
      console.log('推送消息')
      console.log('topic:' + topic)
      console.log('message:' + message)
      this.$mqtt.publish(topic, message)
    }
  },
  mqtt: {
    '#'(data, topic) {
      console.log('mqtt recv!!!')
      console.log('topic:' + topic)
      console.log('payload: ' + String.fromCharCode.apply(null, data))
      if (topic === this.device.pub) {
        var payload = JSON.parse(data)
        console.log(payload)
        console.log('主题正确')
        if (parseInt(payload.aswcode) === CMD_CONTROL.set_auto) {
          if (parseInt(payload.aswmsg) === 1) {
            this.$message({
              type: 'success',
              message: '设置成功'
            })
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>

  .dashboard-editor-container {
    background-color: #e3e3e3;
    min-height: 100vh;
    padding: 50px 60px 0px;
  }
  .position-text{
    color: #ff00ff;
    font-size: 25px;
  }
.text {
    font-size: 20px;
    color: black;
    font-weight: bold;
    margin-left: 10px;
    margin-right: 10px;
}
</style>
